package com.echat.elocation.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.echat.elocation.R;
import com.echat.elocation.base.BaseActivity;
import com.echat.elocation.connect.NettyClient;
import com.echat.elocation.constant.ProtocolConstant;
import com.echat.elocation.event.ConnectionEvent;
import com.echat.elocation.event.UserInfo;
import com.echat.elocation.manager.UserInfoManager;
import com.echat.elocation.protocol.entity.receive.ServerCommonRespMsg;
import com.echat.elocation.service.TerminalService;
import com.echat.elocation.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 *
 * @author lihao
 *
 * @date 2018/7/11 9:36
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "SettingActivity";

    private EditText editHost;
    private EditText editPort;
    private EditText editPhoneNumber;
    private EditText editTerminalId;
    private EditText editCarNumber;
    private EditText editMinTime;

    private boolean isSave;
    private String mHost;
    private int mPort;
    private String mPhoneNumber;
    private String mTerminalId;
    private String mCarNumber;
    private int mMinTime;

    private ProgressDialog progressDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        isSave = UserInfoManager.isSave(this);
        if (isSave) {
            UserInfo info = UserInfoManager.getUserInfo(this);
            mHost = info.getHost();
            mPort = info.getPort();
            mPhoneNumber = info.getPhoneNumber();
            mTerminalId = info.getTerminalId();
            mCarNumber = info.getCarNumber();
            mMinTime = info.getMinTime();
        }
    }

    @Override
    protected void initView() {
        editHost = findViewById(R.id.edit_host);
        editPort = findViewById(R.id.edit_port);
        editPhoneNumber = findViewById(R.id.edit_phone_number);
        editTerminalId = findViewById(R.id.edit_terminalId);
        editCarNumber = findViewById(R.id.edit_car_number);
        editMinTime = findViewById(R.id.edit_min_time);
        Button btnSave = findViewById(R.id.btn_save);
        btnSave.setOnClickListener(this);

        if (isSave) {
            editHost.setText(mHost);
            editPort.setText(String.valueOf(mPort));
            editPhoneNumber.setText(mPhoneNumber);
            editTerminalId.setText(mTerminalId);
            editCarNumber.setText(mCarNumber);
            editMinTime.setText(String.valueOf(mMinTime));
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }

    private void startTerminal() {
        Intent intent = new Intent(this, TerminalService.class);
        startService(intent);
    }

    private void stopTerminal(){
        Intent intent = new Intent(this, TerminalService.class);
        stopService(intent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConnectChange(ConnectionEvent event) {
        if(progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onServerCommonResult(ServerCommonRespMsg event) {
        switch (event.getReplyId()) {
            case ProtocolConstant.msg_id_terminal_authentication:
                if(progressDialog != null) {
                    progressDialog.dismiss();
                }
                if (ServerCommonRespMsg.SUCCESS == event.getReplyCode()) {
                    openActivity(MainActivity.class);
                    finish();
                }
                break;
                default:
                    break;
        }
    }

    /**
     * 检查用户输入的信息是否正确
     *
     * @return
     */
    private boolean checkInput() {
        mHost = editHost.getText().toString().trim();
        mPort = Integer.parseInt(TextUtils.isEmpty(editPort.getText().toString().trim()) ?
                "0" : editPort.getText().toString().trim());
        mPhoneNumber = editPhoneNumber.getText().toString().trim();
        mTerminalId = editTerminalId.getText().toString().trim();
        mCarNumber = editCarNumber.getText().toString().trim();
        mMinTime = Integer.parseInt(TextUtils.isEmpty(editMinTime.getText().toString().trim()) ?
                "0" : editMinTime.getText().toString().trim());
        if (TextUtils.isEmpty(mHost)) {
            ToastUtils.showShort(this, "服务器IP地址为空");
        }
        else if (mPort <= 0) {
            ToastUtils.showShort(this, "服务器端口号为空");
        }
        else if (TextUtils.isEmpty(mPhoneNumber)) {
            ToastUtils.showShort(this, "手机号为空");
        }
        else if (TextUtils.isEmpty(mTerminalId)) {
            ToastUtils.showShort(this, "设备ID为空");
        }
        else if (TextUtils.isEmpty(mCarNumber)) {
            ToastUtils.showShort(this, "车牌号为空");
        }
        else if (mMinTime <= 0) {
            ToastUtils.showShort(this, "定位时间间隔为空");
        }
        else {
            return true;
        }

        return false;
    }

    private void progressDialog(){
        progressDialog = new ProgressDialog(SettingActivity.this);
        progressDialog.setMessage("正在连接...");
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    private void saveConfig(){
        UserInfoManager.clearInfo(this);
        UserInfo info = new UserInfo();
        info.setHost(mHost);
        info.setPort(mPort);
        info.setPhoneNumber(mPhoneNumber);
        info.setTerminalId(mTerminalId);
        info.setCarNumber(mCarNumber);
        info.setMinTime(mMinTime);
        UserInfoManager.setUserInfo(this, info);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_network:
                startActivity(new Intent(Settings.ACTION_SETTINGS));
                break;
            case R.id.btn_save:
                progressDialog();
                if (checkInput()) {
                    saveConfig();
                    ToastUtils.showShort(this, "保存成功");
                    if(NettyClient.getInstance().isConnect()){
                        NettyClient.getInstance().disconnect();
                    }
                    startTerminal();
                }
                break;
            default:
                break;
        }
    }

}
